
// 解构赋值，类似于python的多变量赋值
var arr = [1, 2, 3];
var person = {
    name: '小明',
    age: 20,
    gender: 'male',
    passport: 'G-12345678',
    school: 'No.4 middle school',
    address: {
        city: 'Beijing',
        street: 'No.1 Road',
        zipcode: '100001'
    }
};
var [a, b] = arr;  // array用[],object用{},需要保证嵌套位置一致
var {name, age, address:{ city, street} } = person
// 如果person对象没有single属性，默认赋值为true:
var {gender, single=true} = person;
// 把passport属性赋值给变量id:
let {name, passport:id} = person;

// 使用场景
// 1.交换
var x=1, y=2;
[x, y] = [y, x]；

// 2.访问数组中元素
const colors = [];

let firstColor = 'white';
if (colors.length > 0) {
	firstColor = colors[0]; // firstColor => 'white' 
}

const nums = [1, 2, 3];
const [firstNum = '1'] = nums;
const [, secondNum = 2] = nums;

// 3.不可变操作
const [, ...otherNums] = nums;  // nums.slice(1,num.length)

const big = { foo: 'value Foo', bar: 'value Bar'};

const { foo, ...small } = big; // 放在后边解构，就等价于delete
small; // => { bar: 'value Bar' }
big; // => { foo: 'value Foo', bar: 'value Bar' }

// 4. 解构 iterables
// array, string, typed arrays, set 和 map。
const movies = {
  list: [
    { title: 'Heat' }, 
    { title: 'Interstellar' }
  ],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.list.length) {
          const value = this.list[index++].title;
          return { value, done: false };
        }
        return { done: true };
      }
    };
  } // 自定义迭代器
};
// movies包含一个movie对象列表。在解构movies时，将title作为字符串获取
const [firstMovieTitle] = movies;
console.log(firstMovieTitle); // => 'Heat'


// 5.Obj动态解构
function greet(obj, nameProp) {
 const { [nameProp]: name = 'Unknown' } = obj;
 return `Hello, ${name}!`;
}

// 在greet()内部，解构赋值const {[nameProp]：name ='Unknown'} = obj
// 使用方括号的形式 [nameProp]读取动态属性名称，name变量接收动态属性值。
greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!'
greet({ }, 'name'); // => 'Hello, Unknown!'




